<template>
  <div v-loading="loading" element-loading-text="加载中..." class="warehouse_detail">
    <div class="main">
      <div class="header">
        <div class="title">
          <div class="text_container">
            <i class="iconfont icon-detail"></i>
            <div class="text">
              仓库名称：
              <span>{{ DetailStore?.name }}</span>
            </div>
          </div>
          <HStatus v-permission="'storage_disabled'" v-if="DetailStore?.status" type="info">禁用</HStatus>
          <HStatus v-permission="'storage_enabled'" v-else>启用</HStatus>
        </div>
        <div class="btn_group">
          <HPlainButton v-permission="'storage_update'" @click="showAdd">编辑</HPlainButton>
          <HPlainButton v-permission="'storage_delete'" type="error" @click="deleteClick">删除 </HPlainButton>
        </div>
      </div>
      <div class="divider_line"></div>
      <div class="body">
        <div ref="infoRef" class="info">
          <!-- 基本信息 -->
          <div class="title">仓库信息</div>
          <div class="info_list">
            <div class="info_item_container">
              <div class="info_item">
                <div class="label" style="width: 51px">仓库条码:</div>
                <div class="value">{{ DetailStore?.storeNo }}</div>
              </div>
              <div class="info_item">
                <div class="label" style="width: 51px">管理员:</div>
                <div class="value"
                  >{{ DetailStore?.userName }}&nbsp;{{ DetailStore?.userPhone }}</div
                >
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">负库存:</div>
                <div class="value">{{ DetailStore?.canNegativeStock ? '允许' : '不允许' }}</div>
              </div>
              <div class="info_item">
                <div class="label">仓位:</div>
                <div class="value">{{ DetailStore?.enableStorePosition ? '开启' : '关闭' }}</div>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">创建时间:</div>
                <div class="value">{{ DetailStore?.createTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">更新时间:</div>
                <div class="value">{{ DetailStore?.updateTime }}</div>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">地址:</div>
                <div class="value"
                  >{{ DetailStore?.province }}{{ DetailStore?.city }}{{ DetailStore?.area
                  }}{{ DetailStore?.town }}{{ DetailStore?.address }}</div
                >
              </div>
            </div>
          </div>
        </div>

        <div class="table_container">
          <div class="title">库存明细</div>
          <div class="table">
            <el-table
              :border="true"
              :data="StoreDetailGoodsList"
              resizable
              stripe
              height="100%"
              :header-cell-style="tableHeaderCellStyle"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column
                label="序号"
                fixed="left"
                width="60"
                type="index"
                :align="'center'"
              />
              <template v-if="DetailStore?.enableStorePosition">
                <el-table-column prop="name" show-overflow-tooltip label="仓位" min-width="150">
                  <template #default="scope">
                    <h-link @click="onClickStorePosition(scope.row)">{{ scope.row.name }}</h-link>
                  </template>
                </el-table-column>
                <el-table-column label="状态" min-width="150" fixed="right" :align="'center'">
                  <template #default="scope">
                    <div class="flex_justify_center">
                      <h-status v-if="scope.row.status" type="info">禁用</h-status>
                      <h-status v-else>启用</h-status>
                    </div>
                  </template>
                </el-table-column>
              </template>
              <template v-else>
                <!-- <el-table-column
                  prop="goodsBrand"
                  show-overflow-tooltip
                  label="产品品牌"
                  min-width="150"
                /> -->
                <el-table-column
                  prop="goodsName"
                  show-overflow-tooltip
                  label="产品名称"
                  width="250"
                />
                <el-table-column
                  prop="goodsType"
                  show-overflow-tooltip
                  label="产品分类"
                  width="150"
                />
                <!-- <el-table-column
                  prop="goodsModel"
                  show-overflow-tooltip
                  label="产品型号"
                  min-width="100"
                /> -->
                <el-table-column
                  prop="goodsSpecName"
                  show-overflow-tooltip
                  label="产品规格"
                  min-width="100"
                />
                <el-table-column label="是否为核心件" width="120">
                  <template #default="{ row }">{{ row.coreMaterials ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column
                  prop="goodsUnit"
                  show-overflow-tooltip
                  label="产品单位"
                  width="100"
                />
              </template>
              <el-table-column width="100" show-overflow-tooltip>
                <template #header>
                  <span>可用库存</span>
                  <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </template>
                <template #default="i">
                  <p class="right_text"> {{ i.row.availableStock.toLocaleString() }}</p>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <Pagination
              ref="pagination"
              :list_total="total"
              @size-change="getStoreList"
              @current-change="getStoreList"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 编辑仓库弹窗 -->
    <h-drawer
      v-model="addDialog"
      title="编辑仓库"
      :width="800"
      unit="px"
      :loading="updateWarehouseLoading"
    >
      <el-form
        ref="ruleFormRef"
        :model="storeForm"
        label-position="top"
        :rules="rulesStore"
        class="modal_form_content"
        inline-message
      >
        <el-form-item prop="outStoreExample">
          <template #label>
            <span
              >仓库类型
              <el-tooltip content="创建后不可更改" placement="top">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-select v-model="storeForm.outStoreExample" :disabled="storeForm.id != null" clearable>
            <el-option label="内部仓库" :value="0" />
            <el-option label="网点-外部仓库" :value="1" />
            <el-option label="工程师-外部仓库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model.trim="storeForm.name" clearable placeholder="仓库名称" />
        </el-form-item>
        <el-form-item label="仓库地址" prop="province">
          <SingleAddress ref="addrsDom" :address="addrs" @value-change="addressValChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model.trim="storeForm.address"
            clearable
            class="detail"
            placeholder="请输入详细地址"
            maxlength="200"
          />
        </el-form-item>
        <el-form-item label="仓管" prop="userName">
          <el-input v-model.trim="storeForm.userName" clearable placeholder="仓管名称" />
        </el-form-item>
        <el-form-item label="电话" prop="userPhone">
          <el-input
            v-model.trim="storeForm.userPhone"
            clearable
            maxlength="11"
            placeholder="电话号码"
            @input="storeForm.userPhone = storeForm.userPhone.replace(/[^\d]/g, '')"
          />
        </el-form-item>
        <el-form-item prop="enableStorePosition" class="same_line">
          <template #label>
            <span
              >仓位
              <el-tooltip
                :content="storeForm.id ? '创建后不可更改' : '开启仓位后，产品出入库都要选择仓位'"
                placement="top"
              >
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <div class="switch_container">
            <el-switch
              v-model="storeForm.enableStorePosition"
              :disabled="storeForm.id && storeForm.id != null"
              @change="enableStorePositionValue"
            />
            <span v-if="storeForm.enableStorePosition">启用</span>
            <span v-else>禁用</span>
            <div class="same_line" style="column-gap: 24px; margin-left: 24px">
              <el-form-item label="允许负库存" class="same_line">
                <div class="switch_container">
                  <el-switch v-model="storeForm.canNegativeStock" />
                  <span v-if="storeForm.canNegativeStock">允许</span>
                  <span v-else>不允许</span>
                </div>
              </el-form-item>
              <el-form-item label="仓库状态" class="same_line">
                <div class="switch_container">
                  <el-switch v-model="storeStatus" />
                  <span v-if="storeStatus">启用</span>
                  <span v-else>禁用</span>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form-item>

        <template v-if="storeForm.enableStorePosition">
          <template v-for="(i, index) in storeForm.storePositionVos" :key="index">
            <el-form-item
              :label="index == 0 ? '仓位名称' : ''"
              :prop="`storePositionVos[${index}][name]`"
              :rules="[{ required: true, message: '请输入仓位名称', trigger: ['blur', 'change'] }]"
            >
              <div class="shipping_space">
                <el-input v-model.trim="i.name" clearable placeholder="请输入仓位名称" />
                <div v-if="storeForm.id" class="switch_container">
                  <el-switch v-model="i.status" />
                  <span v-if="i.status">启用</span>
                  <span v-else>禁用</span>
                </div>
                <h-link
                  v-if="storeForm.storePositionVos.length > 1"
                  type="error"
                  @click="deleteItem(i, index)"
                  >删除</h-link
                >
                <h-link v-if="index === 0" @click="addItem">添加</h-link>
              </div>
            </el-form-item>
          </template>
        </template>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="submitForm">保存</HButton>
        <HButton is-modal @click="closeClick"> 取消 </HButton>
      </template>
    </h-drawer>

    <!-- 仓位库存-->
    <h-drawer
      v-model="storePositionDialog"
      :width="70"
      title="仓位库存"
      :loading="storePositionLoading"
    >
      <div class="shipping_space_inventory">
        <div class="header">
          <div class="text">
            <p>
              仓位名称：
              <span>{{ storePositionObj?.name }}</span>
            </p>
            <p>
              仓位状态：
              <h-status v-if="storePositionObj?.status" type="info">禁用</h-status>
              <h-status v-else>启用</h-status>
            </p>
          </div>
          <div class="search">
            <el-input
              v-model.trim="keywordstorePosition"
              clearable
              placeholder="品牌、名称"
              @keyup.enter="getstorePositionListData"
              @clear="getstorePositionListData"
            >
            </el-input>
            <h-button type="primary" @click="getstorePositionListData">
              <el-icon>
                <Search></Search>
              </el-icon>
              搜索
            </h-button>
          </div>
        </div>
        <div class="table">
          <el-table
            :border="true"
            :data="storePositionList"
            resizable
            stripe
            height="100%"
            :header-cell-style="tableHeaderCellStyle"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column label="序号" width="60" type="index" fixed="left" :align="'center'" />
            <el-table-column prop="goodsBrand" show-overflow-tooltip label="品牌" min-width="150" />
            <el-table-column prop="goodsType" show-overflow-tooltip label="类型" min-width="150" />
            <el-table-column prop="goodsName" show-overflow-tooltip label="名称" min-width="100" />
            <el-table-column prop="goodsModel" show-overflow-tooltip label="型号" min-width="100" />
            <el-table-column
              prop="goodsSpecName"
              show-overflow-tooltip
              label="规格"
              min-width="100"
            />
            <el-table-column prop="goodsUnit" show-overflow-tooltip label="单位" width="100" />
            <el-table-column min-width="100" show-overflow-tooltip>
              <template #header>
                <span>可用库存</span>
                <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                  <el-icon>
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </template>
              <template #default="i">
                <p class="right_text"> {{ i.row.availableStock.toLocaleString() }}</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="paginationRef"
            :list_total="total_storePosition"
            @size-change="getstorePositionListData"
            @current-change="getstorePositionListData"
          />
        </div>
      </div>
    </h-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, nextTick, CSSProperties, onUnmounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { useRoute } from 'vue-router'
  import { phone, setProvince } from '@/utils/validate'
  import { QuestionFilled } from '@element-plus/icons-vue'
  import { tableHeaderCellStyle } from '@/utils/tools'
  import SingleAddress from './../../../../components/address/singleAddress.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Pagination from './../../../../components/Pagination/index.vue'
  import {
    getStoreDetailGoodsList,
    saveStore,
    deleteStore,
    getStorePositionList,
    getDetailStore,
    getStorePositionDetailGoodsList,
  } from '@/api/store'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.storage.sotrageDetail,
  })

  const infoRef = ref<HTMLDivElement | null>(null)
  const tableContainerStyle = ref<CSSProperties>({})
  const setTableContainerStyle = () => {
    if (infoRef.value) {
      tableContainerStyle.value.height = `calc(100% - ${infoRef.value.scrollHeight}px - -36px)`
    }
  }

  const storePositionDialog = ref(false) //仓位开启点击仓位弹窗
  const storePositionLoading = ref(false) //获取仓位加载...
  const storePositionList = ref([]) //仓位列表数据
  const storePositionObj = ref(null) //点击的仓位数据
  const keywordstorePosition = ref('')
  const paginationRef = ref()
  const total_storePosition = ref(0)
  const onClickStorePosition = (obj) => {
    storePositionObj.value = obj
    storePositionDialog.value = true
    nextTick(() => {
      getstorePositionListData()
    })
  }
  // 获取仓位列表
  const getstorePositionListData = async () => {
    storePositionLoading.value = true
    let data = {
      page: paginationRef.value.current, //当面页码
      name: keywordstorePosition.value,
      limit: paginationRef.value.size, //当面页码
    }
    await getStorePositionDetailGoodsList(data, storePositionObj.value.id).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          storePositionList.value = res.data.data.rows
          total_storePosition.value = Number(res.data.data.total)
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      }
    })
    storePositionLoading.value = false
  }

  const ruleFormRef = ref()
  const addrsDom = ref()
  const storeStatus = ref(true) // 仓库状态
  const storeForm = ref({
    address: '',
    area: '',
    canNegativeStock: false, //是否允许负库存：false-不允许，true-允许
    city: '',
    delStorePositionIds: [], //	删除的仓库仓位ID集合
    enableStorePosition: false, //是否启用仓位：false-不启用，true-启用
    id: null, //
    name: '', //仓库名称
    otherPhone: '', //其他联系方式
    outStoreExample: 0, // 仓库类型：0-内部仓库，1-网点-外仓库，2-工程师-外仓库
    outStore: false, //仓库类型：false-内部仓库，true-外部仓库
    outStoreType: 1, //外部仓库类型：1-网点仓库，2-工程师仓库，当is_out_store=true时生效,示例值(1)
    province: '',
    status: true, //	仓库状态：false-启用，true-禁用，取反值
    storeNo: '', //仓库条码，不传则系统生成
    storePositionVos: [
      //仓库仓位对象
      {
        id: null, //仓位ID，新增不必传，修改必传
        name: '', //仓位
        status: false, //仓位状态：false-启用，true-禁用
      },
    ],
    town: '',
    userName: '',
    userPhone: '',
  })
  const rulesStore = reactive({
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }], //仓库名称
    outStoreExample: [{ required: true, message: '仓库类型', trigger: 'change' }], //仓库类型：false-内部仓库，true-外部仓库
    userName: [{ required: true, message: '请输入仓库联系人', trigger: 'blur' }],
    userPhone: [
      { required: true, message: '请输入联系人手机号', trigger: 'blur' },
      { validator: phone(storeForm.value.userPhone), trigger: 'blur' },
    ],
    province: [
      {
        required: true,
        validator: setProvince(storeForm.value.province),
        trigger: ['blur', 'change'],
      },
    ],
  })
  const TagsViewStore = useTagsViewStore()
  const addDialog = ref(false)
  const router = useRouter()
  const route = useRoute()
  const StoreDetailGoodsList = ref()
  const total = ref(0)

  const loading = ref(false)
  const pagination = ref()
  const storeListRef = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 所属地址
  function addressValChange() {
    addrs.value = addrsDom.value.getSelectAddr()
    storeForm.value.province = addrs.value.province
    storeForm.value.city = addrs.value.city
    storeForm.value.area = addrs.value.area
    storeForm.value.town = addrs.value.town
  }
  // 保存添加仓库
  const updateWarehouseLoading = ref(false)
  const submitForm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        updateWarehouseLoading.value = true
        loading.value = true
        if (storeForm.value.outStoreExample == 0) {
          storeForm.value.outStore = false
        }
        if (storeForm.value.outStoreExample > 0) {
          storeForm.value.outStore = true
          storeForm.value.outStoreType = storeForm.value.outStoreExample
        }
        storeForm.value.status = !storeStatus.value
        if (storeForm.value.enableStorePosition) {
          storeForm.value.storePositionVos = storeForm.value.storePositionVos.map((o) => {
            return { ...o, status: !o.status }
          })
        }
        saveStore(storeForm.value).then((res) => {
          updateWarehouseLoading.value = false
          if (res) {
            if (res.data.code == 20000) {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
              })
              getDetailStoreItem()
              closeClick()
            } else {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 5000,
                plain: true,
              })
            }
          }
          loading.value = false
        })
      }
    })
  }
  // 删除仓库
  const deleteClick = () => {
    let ids = [storeForm.value.id]

    ElMessageBox({
      title: '提示',
      message: `确定要删除仓库?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'error',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    }).then(async () => {
      await deleteStore(ids).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
            })
            if (addDialog.value) {
              addDialog.value = false
            }
            TagsViewStore.delView(route.path)
            router.push('/storage/list')
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
            })
          }
        }
        loading.value = false
      })
    })
  }
  // 显示编辑弹窗
  const showAdd = () => {
    addDialog.value = true
  }
  const DetailStore = ref()
  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async () => {
    loading.value = true
    await getDetailStore(route.params.id).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          const data = res.data.data.row
          DetailStore.value = res.data.data.row
          storeForm.value = {
            ...data,
            outStoreExample: data.outStore == false ? 0 : data.outStoreType,
          }
          storeForm.value.storePositionVos = res.data.data.row.storePositionVos.map((o) => {
            return { ...o, status: !o.status }
          })
          storeStatus.value = !storeForm.value.status
          // storeForm.value.outStoreExample = data.outStore == false ? 0 : data.outStoreType
          addrs.value = {
            province: res.data.data.row.province,
            city: res.data.data.row.city,
            area: res.data.data.row.area,
            town: res.data.data.row.town,
          }
          getStoreList()
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      }
    })
    loading.value = false
  }
  // 添加仓库仓位
  const addItem = () => {
    storeForm.value.storePositionVos.push({
      id: null, //仓位ID，新增不必传，修改必传
      name: '', //仓位
      status: false, //仓位状态：false-启用，true-禁用
    })
    storeListRef.value.scrollTop = storeListRef.value.scrollHeight
  }

  // 删除仓库位
  const deleteItem = (i, index) => {
    if (storeForm.value.storePositionVos.length == 1) {
      ElMessage({
        showClose: true,
        duration: 5000,
        plain: true,
        type: 'warning',
        message: '必须保留至少一个仓位！',
      })
      return
    }
    if (!storeForm.value.delStorePositionIds) {
      storeForm.value.delStorePositionIds = []
    }

    storeForm.value.storePositionVos = storeForm.value.storePositionVos.filter((o, n) => {
      if (index == n && i.id) {
        storeForm.value.delStorePositionIds.push(i.id)
      }
      return n !== index
    })
    if (storeForm.value.storePositionVos.length == 0) {
      storeForm.value.enableStorePosition = false
    }
  }
  // 监听仓库位是否开启
  const enableStorePositionValue = (n) => {
    if (n) {
      if (!storeForm.value.storePositionVos) {
        storeForm.value.storePositionVos = [
          {
            id: null, //仓位ID，新增不必传，修改必传
            name: '', //仓位
            status: false, //仓位状态：false-启用，true-禁用
          },
        ]
      }
    } else {
      storeForm.value.storePositionVos.filter((o) => {
        if (o.id) {
          storeForm.value.delStorePositionIds.push(o.id)
        }
      })
    }
  }
  // 关闭取消
  const closeClick = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    addDialog.value = false
  }
  //库存明细列表
  const getStoreList = async () => {
    loading.value = true
    if (route.params.id) {
      let data = {
        page: pagination.value.current, //当面页码
        name: '',
        limit: pagination.value.size, //当面页码
      }
      if (DetailStore.value?.enableStorePosition) {
        await getStorePositionList(data, route.params.id).then((res) => {
          if (res) {
            if (res.data.code == 20000) {
              StoreDetailGoodsList.value = res.data.data.rows
              total.value = Number(res.data.data.total)
            } else {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 5000,
                plain: true,
              })
            }
          }
        })
      } else {
        await getStoreDetailGoodsList(data, route.params.id).then((res) => {
          if (res) {
            if (res.data.code == 20000) {
              StoreDetailGoodsList.value = res.data.data.rows
              total.value = Number(res.data.data.total)
            } else {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 5000,
                plain: true,
              })
            }
          }
        })
      }
    }
    loading.value = false
  }

  onMounted(() => {
    getDetailStoreItem()
    setTableContainerStyle()
    window.addEventListener('resize', setTableContainerStyle)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', setTableContainerStyle)
  })
</script>

<style lang="scss" scoped>
  @import './detail';
</style>
